package com.cskaoyan.service.wx_order_before;

import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.goods.Goods;
import com.cskaoyan.bean.mall.order.Order;
import com.cskaoyan.bean.mall.order.OrderExample;
import com.cskaoyan.bean.promote.Coupon;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wx_OrderGoods.OrderGoods;
import com.cskaoyan.bean.wx_OrderGoods.OrderGoodsExample;
import com.cskaoyan.bean.wx_address.AddressVO;
import com.cskaoyan.bean.wx_cart.Cart;
import com.cskaoyan.bean.wx_order_before.base.OrderBeforePageData;
import com.cskaoyan.bean.wx_order_before.base.OrderBeforeParam;
import com.cskaoyan.bean.wx_order_before.bo.OrderSubmitBo;
import com.cskaoyan.bean.wx_order_before.vo.GoodsListBean;
import com.cskaoyan.bean.wx_order_before.vo.HandleOptionBean;
import com.cskaoyan.bean.wx_order_before.vo.OrderBeforeShowTypeVo;
import com.cskaoyan.controller.wx_order_before.exception.SubmitOrderException;
import com.cskaoyan.mapper.goods.GoodsMapper;

import com.cskaoyan.mapper.mall.OrderMapper;
import com.cskaoyan.mapper.promote.CouponMapper;
import com.cskaoyan.mapper.user.AddressMapper;
import com.cskaoyan.mapper.wx_OrderGoods.OrderGoodsMapper;

import com.cskaoyan.mapper.wx_cart.CartMapper;
import com.cskaoyan.service.wx_order_before.utils.OrderStatusUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WXOrderServiceImplBefore implements WXOrderServiceBefore {

    private static final int ALL_ORDERS = 0;
    private static final short ORDER_STATUS = 101;
    private static final short ORDER_PREPAY = 201;
    private static final short AFTERSALE_STATUS = 0;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public OrderBeforePageData listOrders(Integer showType, OrderBeforeParam orderBeforeParam) {
        //分页插件
        PageHelper.startPage(orderBeforeParam.getPage(),orderBeforeParam.getLimit());
        //获取subject中的user对象
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        //根据showType和userId查询订单 → 当前状态下该用户的订单信息
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        if (showType != ALL_ORDERS){//不等于0，说明查询的不是全部订单
            Short[] status = OrderStatusUtils.getOrderStatus().get(showType);
            List<Short> statusList = new ArrayList<>(Arrays.asList(status));
            criteria.andOrderStatusIn(statusList);
        }
        criteria.andUserIdEqualTo(user.getId()).andDeletedEqualTo(false);
        List<Order> orders = orderMapper.selectByExample(example);
        //获取订单状态信息map
        Map<Integer, String> statusText = OrderStatusUtils.getOrderStatusText();
        //获取订单信息
        ArrayList<OrderBeforeShowTypeVo> orderBeforeShowTypeVos = new ArrayList<>();
        for (Order order : orders) {
            OrderBeforeShowTypeVo typeVo = new OrderBeforeShowTypeVo();
            int state = order.getOrderStatus();
            typeVo.setOrderStatusText(statusText.get(state));
            typeVo.setAftersaleStatus(order.getAftersaleStatus());
            BigDecimal bd2 = new BigDecimal(0);
            if (bd2.compareTo(order.getGrouponPrice()) == 0){
                typeVo.setIsGroupin(false);
            }else {
                typeVo.setIsGroupin(true);
            }
            typeVo.setOrderSn(order.getOrderSn());
            typeVo.setActualPrice(order.getActualPrice());
            typeVo.setId(order.getId());
            typeVo.setHandleOption(OrderStatusUtils.getHandleOptionBeanByOrderStateMap().get(showType));

            OrderGoodsExample goodsExample = new OrderGoodsExample();
            OrderGoodsExample.Criteria exampleCriteria = goodsExample.createCriteria();
            exampleCriteria.andOrderIdEqualTo(order.getId());
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(goodsExample);
            ArrayList<GoodsListBean> goodsListBeans = new ArrayList<>();
            for (OrderGoods orderGoods : orderGoodsList) {
                goodsListBeans.add(new GoodsListBean(orderGoods.getNumber(),orderGoods.getPicUrl(),orderGoods.getPrice(),orderGoods.getId(),orderGoods.getGoodsName(),orderGoods.getSpecifications()));
            }

            typeVo.setGoodsList(goodsListBeans);

            orderBeforeShowTypeVos.add(typeVo);
        }

        return OrderBeforePageData.ok(orderBeforeShowTypeVos);
    }

    @Override
    public void submitOrder(OrderSubmitBo orderSubmitBo) throws SubmitOrderException {
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Order order = new Order();
        OrderGoods orderGoods = new OrderGoods();
        //order
        order.setUserId(user.getId());
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        String dateString = formatter.format(currentTime);
        order.setOrderSn(dateString);
        order.setOrderStatus(ORDER_STATUS);
        order.setAftersaleStatus(AFTERSALE_STATUS);

        //address to order
        Address address = addressMapper.selectByPrimaryKey(orderSubmitBo.getAddressId());
        order.setConsignee(address.getName());
        order.setMobile(address.getTel());
        order.setAddress(address.getAddressDetail());

        //order message
        order.setMessage(orderSubmitBo.getMessage());

        //下单了，删除购物车中商品
        Cart deleteCart = new Cart();
        deleteCart.setId(orderSubmitBo.getCartId());
        deleteCart.setDeleted(true);
        cartMapper.updateByPrimaryKeySelective(deleteCart);

        //cart
        Cart cart = cartMapper.selectByPrimaryKey(orderSubmitBo.getCartId());
        BigDecimal goodsPrice = cart.getPrice().multiply(new BigDecimal(cart.getNumber()));
        order.setGoodsPrice(goodsPrice);
        order.setFreightPrice(new BigDecimal(0));

        //coupon
        Coupon coupon = couponMapper.selectByPrimaryKey(orderSubmitBo.getCouponId());
        if (coupon != null){
            order.setCouponPrice(coupon.getDiscount());
        }else {
            order.setCouponPrice(new BigDecimal(0));
        }
        order.setIntegralPrice(new BigDecimal(0));
        order.setGrouponPrice(new BigDecimal(0));

        //订单费用和实付费用
        BigDecimal orderPrice = goodsPrice.add(new BigDecimal(0));
        if (coupon != null){
            orderPrice = orderPrice.subtract(coupon.getDiscount());
        }
        order.setOrderPrice(orderPrice);
        order.setActualPrice(orderPrice.subtract(new BigDecimal(0)));


        //wx
        order.setPayId(user.getWeixinOpenid());
        Date date = new Date(System.currentTimeMillis());
        order.setPayTime(date);

        order.setAddTime(date);
        order.setUpdateTime(date);

        order.setDeleted(false);

        int code = orderMapper.insert(order);
        if (code == 0) throw new SubmitOrderException();

        //orderGoods

        orderGoods.setOrderId(order.getId());
        orderGoods.setGoodsId(cart.getGoodsId());
        orderGoods.setGoodsSn(cart.getGoodsSn());
        orderGoods.setGoodsName(cart.getGoodsName());
        orderGoods.setProductId(cart.getProductId());
        orderGoods.setNumber(cart.getNumber());
        orderGoods.setPrice(goodsPrice);

        Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());

        orderGoods.setSpecifications(goods.getGallery());
        orderGoods.setPicUrl(goods.getPicUrl());
        orderGoods.setComment(0);
        orderGoods.setAddTime(date);
        orderGoods.setUpdateTime(date);
        orderGoods.setDeleted(false);

        orderGoodsMapper.insertSelective(orderGoods);

    }

    @Override
    public void orderPrepay(Integer orderId) throws SubmitOrderException {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus(ORDER_PREPAY);
        int code = orderMapper.updateByPrimaryKeySelective(order);
        if (code == 0) throw new SubmitOrderException();
    }


}
